﻿// -----------------------------------------------------------------------
// <copyright file="TablePermissionDto.cs" company="JSC Centido">
//  Copyright (c) JSC Centido. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;

namespace Centido.Core.Dto
{
    /// <summary>
    ///   A data transfer object for a table permission.
    /// </summary>
    public class TablePermissionDto : DataTransferObject
    {
        /// <summary>
        ///   The name of the xml tag that is used to store this object.
        /// </summary>
        public const string XmlTag = "permission";

        /// <summary>
        ///   The current xml schema version.
        /// </summary>
        public const string CurrentXmlSchemaVersion = "1";

        /// <summary>
        ///   The name of the xml attribute to store the principal name.
        /// </summary>
        public const string PrincipalNameAttribute = "principal";

        /// <summary>
        ///   The name of the xml attribute to store the allowed data action.
        /// </summary>
        public const string DataActionAttribute = "action";

        /// <summary>
        ///   The name of the xml attribute to store the access level.
        /// </summary>
        public const string AccessLevelAttribute = "level";


        /// <summary>
        ///   Gets or sets the principal name.
        /// </summary>
        public string PrincipalName { get; set; }


        /// <summary>
        ///   Gets or sets the allowed data action.
        /// </summary>
        public DataAction DataAction { get; set; }


        /// <summary>
        ///   Gets or sets the access level.
        /// </summary>
        public AccessLevel AccessLevel { get; set; }


        /// <summary>
        ///   This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
        /// </summary>
        /// <returns>
        ///   An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
        /// </returns>
        public override XmlSchema GetSchema()
        {
            return null;
        }


        /// <summary>
        ///   Generates an object from its XML representation.
        /// </summary>
        /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. 
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="reader"/> is null.</exception>
        public override void ReadXml(XmlReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            reader.MoveToContent();

            // Reading the xml schema version
            var xmlSchemaVersion = ReadStringAttribute(reader, XmlSchemaVersionTag, isRequired: false);

            // If the xml schema version is not defined
            if (string.IsNullOrEmpty(xmlSchemaVersion)
                // or if it is the current xml schema version
                || xmlSchemaVersion == CurrentXmlSchemaVersion)
            {
                // Reading the principal name
                PrincipalName = ReadStringAttribute(reader, PrincipalNameAttribute);

                // Reading the data action
                DataAction = (DataAction)ReadEnumAttribute(reader, DataActionAttribute, typeof(DataAction))
                    .GetValueOrDefault();

                // Reading the access level
                AccessLevel = (AccessLevel)ReadEnumAttribute(reader, AccessLevelAttribute, typeof(AccessLevel))
                    .GetValueOrDefault();

                var isEmptyElement = reader.IsEmptyElement;

                reader.ReadStartElement();

                if (!isEmptyElement)
                    reader.ReadEndElement();
            }
            else
                throw new ArgumentException(string.Format(
                    "The specified xml schema version is not supported (node = {0}, version = {1}).",
                    reader.Name,
                    xmlSchemaVersion));
        }


        /// <summary>
        ///   Converts an object into its XML representation.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. 
        /// </param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="writer"/> is null.</exception>
        public override void WriteXml(XmlWriter writer)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.WriteStartElement(XmlTag);

            // The xml schema version
            writer.WriteAttributeString(XmlSchemaVersionTag, CurrentXmlSchemaVersion);

            // The principal name
            if (!string.IsNullOrEmpty(PrincipalName))
                writer.WriteAttributeString(PrincipalNameAttribute, PrincipalName);

            // The data action
            writer.WriteAttributeString(DataActionAttribute, 
                ((int)DataAction).ToString(CultureInfo.InvariantCulture));

            // The access level
            writer.WriteAttributeString(AccessLevelAttribute, 
                ((int)AccessLevel).ToString(CultureInfo.InvariantCulture));

            writer.WriteEndElement();
        }


        /// <summary>
        ///   Creates a data transfer object for the specified table permission.
        /// </summary>
        /// <param name="tablePermission">The specified table permission.</param>
        /// <exception cref="ArgumentNullException">Thrown when the value of <paramref name="tablePermission"/> is null.</exception>
        /// <returns>Returns the data transfer object for the specified table permission.</returns>
        public static TablePermissionDto CreateFrom(TablePermission tablePermission)
        {
            if (tablePermission == null)
                throw new ArgumentNullException("tablePermission");

            var tablePermissionDto = new TablePermissionDto
            {
                PrincipalName = tablePermission.Principal.Name,
                DataAction = tablePermission.DataAction,
                AccessLevel = tablePermission.AccessLevel
            };

            return tablePermissionDto;
        }
    }
}
